﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;

namespace Common
{
    public class FtpClient
    {
        private static int m_BuffSize = 2048;

        public static void UploadFile(FileInfo fileInfo, string account, string password, string url)
        {
            

            FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(url);
            ftpRequest.Credentials = new NetworkCredential(account, password);
            ftpRequest.KeepAlive = false;
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpRequest.UseBinary = true;
            ftpRequest.ContentLength = fileInfo.Length;
            ftpRequest.Proxy = new WebProxy();

            byte[] requestByte = new byte[m_BuffSize];

            int contentLen = 0;

            FileStream fileStream = null;
            Stream uploadStream = null;
            try
            {
                fileStream = fileInfo.OpenRead();

                uploadStream = ftpRequest.GetRequestStream();

                do
                {
                    contentLen = fileStream.Read(requestByte, 0, m_BuffSize);
                    uploadStream.Write(requestByte, 0, contentLen);
                }
                while (contentLen > 0);
            }
            catch(Exception ex)
            {
                Log.WriteException(ex);
                throw new Exception("由于网络原因导致文件上传失败");                
            }
            finally
            {                
                fileStream?.Dispose();
                uploadStream?.Dispose();
            }
        }
    }
}
